// 路由守卫
import router from "./router";
//@ts-expect-error
import nprogress from "nprogress";
nprogress.configure({ showSpinner: false });
// 获取用户相关的小仓库
import useUserStore from "./store/modules/user";
import pinia from "./store";
import setting from "./setting";
let userStore = useUserStore(pinia);

// 全局前置守卫
router.beforeEach(async (to, _, next) => {
  nprogress.start();
  let token = userStore.token;
  // 获取用户名字
  let username = userStore.username;
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next({ ...to, replace: true });
        } catch (error) {
          await userStore.userLoginOut();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    // 用户未登录
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

// 全局后置守卫
router.afterEach((to) => {
  document.title = setting.title + "-" + to.meta.title;
  nprogress.done();
});
